<template>
  <div class="bigbox" v-if="istreeshow">
    <div class="liftbox">
      <div>
        <template>
          <!-- <el-select ref="select" clearable
             @change="cahange"
             v-model="input1" filterable placeholder="请选择" @keyup.enter.native="changinput1" style="width: 280px;">
                <el-option
                class="select"
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select> -->
          <el-autocomplete
            class="inline-input"
            v-model="filterText"
            style="width: 100%"
            :fetch-suggestions="querySearch"
            placeholder="输入关键字进行过滤"
            :trigger-on-focus="true"
            value-key="name"
            size="small"
            :debounce="300"
            @select="handleSelect"
          ></el-autocomplete>
        </template>
      </div>
      <div class="treebox">
        <!-- 树状图区域结构 -->
        <el-tree
          :props="props"
          :load="loadNode"
          node-key="id"
          accordion
          :highlight-current="true"
          :default-expanded-keys="array"
          lazy
          @node-click="handleNodeClick"
          ref="tree"
        >
          <template slot-scope="{ node, data }">
            <span
              :style="{
                color: data.collect
                  ? ''
                  : data.className == 'FactoryStation'
                  ? '#999'
                  : '',
                'font-size': data.collect
                  ? ''
                  : data.className == 'FactoryStation'
                  ? '14px'
                  : ''
              }"
            >
              <img
                :src="'data:image/png;base64,' + data.iconBase64"
                style="
                  width: 16px;
                  height: 16px;
                  margin-right: 5px;
                  vertical-align: bottom;
                "
              />{{ node.label }}</span
            >
          </template>
        </el-tree>
      </div>
    </div>
    <div class="rightbox">
      <div class="title">{{ row.name }} 测点列表</div>
      <div class="righttop">
        <div>
          <template>
            <el-select
              v-model="form.region"
              clearable
              placeholder="测点分组"
              size="small"
              style="margin-right: 10px"
              @change="changeselectdan"
            >
              <el-option
                class="select"
                v-for="(item, index) in xlalalist"
                :key="index"
                :label="item.text"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-input
              placeholder="请输入测点名称搜索"
              suffix-icon="el-icon-search"
              @keyup.enter.native="changeinput"
              v-model="input2"
              style="width: 200px; height: 32px"
              size="small"
            ></el-input>
          </template>
        </div>
        <div class="button">
          <el-dropdown @command="handleCommand">
            <el-button type="primary" size="small" style="margin-right: 10px">
              新 增 <i class="el-icon-arrow-down" style="font-size: 12px"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="moban" style="padding: 0 10px"
                ><span>模板方式</span></el-dropdown-item
              >
              <el-dropdown-item command="fuzhi" style="padding: 0 10px"
                ><span>复制方式</span></el-dropdown-item
              >
              <el-dropdown-item command="zhiyou" style="padding: 0 10px"
                ><span>自由方式</span></el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
          <el-button @click="daoru" size="small">测点导入</el-button>
          <el-button size="small" @click="newxuni">新增虚拟测点</el-button>
          <el-button size="small" @click="pilianggai">批量修改</el-button>
          <el-button size="small" @click="dellist">批量删除</el-button>
          <el-button size="small" @click="daochu">导 出</el-button>
          <!-- <el-button @click="daochu">导出</el-button> -->
        </div>
      </div>
      <div class="tablebox">
        <template>
          <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            v-loading="loading"
            style="width: 100%"
            border
            height="calc(100% - 1px)"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center'
            }"
            @selection-change="handleSelectionChange"
          >
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <el-table-column type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column label="采集设备" prop="iotSourceName">
            </el-table-column>
            <el-table-column prop="itemTag" label="测点标识"> </el-table-column>
            <el-table-column prop="itemName" label="测点名称">
            </el-table-column>
            <el-table-column label="测点地址" prop="dataAddress">
            </el-table-column>
            <el-table-column prop="dataRate" label="倍率" align="right">
            </el-table-column>
            <el-table-column prop="itemGroup" label="测点分组" align="center">
              <template #default="{ row }">
                <span>{{
                  xlalalist.filter((ele) => ele.value == row.itemGroup)[0]?.text
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" width="200">
              <template #default="{ row }">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="告警配置"
                  placement="top-end"
                >
                  <span
                    v-if="row.dataType == 'YC'"
                    @click="$refs.ElDialogsrefs.getmethod(row, 'itemId')"
                    ><i
                      class="iconfont icon-gaojing1"
                      style="
                        color: skyblue;
                        margin-right: 15px;
                        cursor: pointer;
                      "
                    ></i
                  ></span>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="计算公式"
                  placement="top-end"
                >
                  <span
                    v-if="row.iotSource == '1'"
                    @click="putjisuangongsi(row)"
                    ><i
                      class="iconfont icon-xiugaimima"
                      style="
                        color: skyblue;
                        margin-right: 15px;
                        cursor: pointer;
                      "
                    ></i
                  ></span>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="修改"
                  placement="top-end"
                >
                  <span @click="putlists(row)"
                    ><i
                      class="el-icon-edit"
                      style="
                        color: skyblue;
                        margin-right: 15px;
                        cursor: pointer;
                      "
                    ></i
                  ></span>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top-end"
                >
                  <span @click="dellist(row)"
                    ><i
                      class="el-icon-delete"
                      style="color: red; margin-right: 15px; cursor: pointer"
                    ></i
                  ></span>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="上移"
                  placement="top-end"
                >
                  <span @click="shangyi(row)"
                    ><i
                      class="el-icon-upload2"
                      style="
                        color: skyblue;
                        margin-right: 15px;
                        cursor: pointer;
                      "
                    ></i
                  ></span>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="下移"
                  placement="top-end"
                >
                  <span @click="xiayi(row)"
                    ><i
                      class="el-icon-download"
                      style="
                        color: skyblue;
                        margin-right: 15px;
                        cursor: pointer;
                      "
                    ></i
                  ></span>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <div class="fenye">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="pageNo"
          @current-change="getshebeilist(value, val)"
          :page-size="20"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 模板新增弹出框 -->
    <DialogMuban
      :value="value"
      ref="dialogmuban"
      :row="row ? row : {}"
      @shuxing="shuxing"
    ></DialogMuban>
    <!-- 非模板新增弹出框 -->
    <DialogFeimuban
      :value="value"
      ref="dialogfeimuban"
      :row="row ? row : {}"
      @shuxing="shuxing"
    ></DialogFeimuban>
    <!-- 批量修改遥测数据类型组件 -->
    <DialogYaoce
      ref="dialogyaoce"
      :flag="'flag'"
      :changeselect="changeselect"
      @shuxing="shuxing"
    >
    </DialogYaoce>
    <!-- 批量修改遥信数据类型组件 -->
    <DialogYaoxin
      ref="dialogyaoxin"
      :changeselect="changeselect"
      :flag="'flag'"
      @shuxing="shuxing"
    ></DialogYaoxin>
    <!-- 批量修改累计数据类型组件 -->
    <DialogLeiji
      ref="dialogleiji"
      :changeselect="changeselect"
      :flag="'flag'"
      @shuxing="shuxing"
    >
    </DialogLeiji>
    <!-- 批量修改遥控数据类型组件 -->
    <DialogYaokong
      ref="dialogyaokong"
      :changeselect="changeselect"
      :flag="'flag'"
      @shuxing="shuxing"
    ></DialogYaokong>
    <!-- 批量修改遥调数据类型组件 -->
    <DialogYaotiao
      ref="dialogyaotiao"
      :changeselect="changeselect"
      :flag="'flag'"
      @shuxing="shuxing"
    ></DialogYaotiao>
    <!-- 复制新增弹出框 -->
    <div>
      <el-dialog title="复制新增" :visible.sync="dialogVisibles" width="30%">
        <div>
          <el-form :model="formdata" :rules="rules" ref="form">
            <el-form-item label="复制设备:" prop="fuzhi">
              <el-select
                v-model="formdata.fuzhi"
                placeholder="请选择复制设备"
                filterable
                style="width: 250px"
                size="mini"
                ref="selects"
              >
                <template v-slot:prefix>
                  <span>从</span>
                </template>
                <el-option
                  class="select"
                  v-for="(item, index) in xlalalists"
                  :key="index"
                  :label="item.text"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="采集设备:" prop="caiji">
              <el-select
                v-model="formdata.caiji"
                placeholder="请选择采集设备"
                filterable
                style="width: 250px"
                size="mini"
              >
                <template v-slot:prefix>
                  <span>至</span>
                </template>
                <el-option
                  class="select"
                  v-for="(item, index) in xlalalistss"
                  :key="index"
                  :label="item.text"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="button">
          <el-button type="primary" @click="submit" size="small"
            >确 定</el-button
          >
          <el-button @click="quxiaofuzhi" size="small">取 消</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 告警配置 -->
    <ElDialogs ref="ElDialogsrefs"></ElDialogs>
    <!-- 虚拟测点新增 -->
    <div>
      <XniCedian
        ref="xunicedian"
        :value="value"
        @shuaxin="shuaxin"
        :isxunicedianobj="isxunicedianobj"
        @qingkong="isxunicedianobj = {}"
      ></XniCedian>
    </div>
    <!-- 导入导出测点 -->
    <ExportorInport
      ref="ExportorInport"
      :value="value"
      @shuxing="shuxing"
    ></ExportorInport>
  </div>
</template>

<script>
import axios from 'axios'
import { getxialafenzuapi } from '@/api/ElectricalDistribution/IotTechnology/eventtype.js'
import {
  getshebeilistapi,
  getgenjiedianapi,
  getzijidianapi,
  getsousuoapi,
  getfuzhiapi,
  getcaijiapi,
  postfuzizenapi,
  dellistapi,
  postshangyiapi,
  postxiayiapi,
  getDevicePageapi
} from '@/api/ElectricalDistribution/IotTechnology/device'
import DialogMuban from './mubanxin.vue'
import DialogFeimuban from './feimuban.vue'
import DialogYaoce from '@/views/ElectricalDistribution/IotTechnology/measure/yaoce.vue'
import DialogYaoxin from '@/views/ElectricalDistribution/IotTechnology/measure/yaoxin.vue'
import DialogLeiji from '@/views/ElectricalDistribution/IotTechnology/measure/leiji.vue'
import DialogYaokong from '@/views/ElectricalDistribution/IotTechnology/measure/yaokong.vue'
import DialogYaotiao from '@/views/ElectricalDistribution/IotTechnology/measure/yaotiao.vue'
import XniCedian from './xunicedian.vue'
import ExportorInport from './ExportorInport.vue'
import ElDialogs from '../component/dialog-el.vue'
export default {
  name: 'MaintenanceIndex',
  components: {
    DialogMuban,
    DialogFeimuban,
    DialogYaoce,
    DialogYaoxin,
    DialogLeiji,
    DialogYaokong,
    DialogYaotiao,
    XniCedian,
    ExportorInport,
    ElDialogs
  },
  data() {
    return {
      formdata: {},
      rules: {
        fuzhi: [{ required: true, message: '复制设备必选', trigger: 'blur' }],
        caiji: [{ required: true, message: '采集设备必选', trigger: 'blur' }]
      },
      props: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      dialogVisibles: false,
      treedata: {},
      xlalalist: [],
      form: {},
      val: '',
      input1: '',
      input2: '',
      tableData: [],
      value: '',
      options: [],
      option: [],
      row: '',
      xlalalists: [],
      xlalalistss: [],
      mulist: [],
      changeselect: [],
      filterlist: [],
      isxunicedianobj: {},
      array: ['503750'],
      filterText: '',
      total: 0,
      pageNo: 0,
      pageSize: 20,
      loading: false,
      istreeshow: false
    }
  },
  async created() {},
  async mounted() {
    if (this.$route.params.treeModel) this.istreeshow = true
    const res = await getxialafenzuapi({ dictType: 'MeasurementKind' })
    this.xlalalist = res.data.list
  },
  methods: {
    async getcaijixialalist(id) {
      try {
        const ress = await getfuzhiapi({ deviceId: id })
        this.xlalalists = ress.data.list
      } catch (error) {
        this.xlalalists = []
      }
      try {
        const resss = await getcaijiapi({ deviceId: id })
        this.xlalalistss = resss.data.list
        //  this.xlalalistss.forEach(ele=>this.filterlist.push(ele))
      } catch (error) {
        this.xlalalistss = []
      }
    },
    async loadNode(node, resolve) {
      const treeModel = this.$route.params.treeModel
      if (node.level === 0) {
        // 初始的级数（最顶层）
        const res = await getgenjiedianapi({ treeModel: treeModel })
        // const res = await getgenjiedianapi({ treeModel: 'DeviceManageTree' })
        var ress = await getzijidianapi(res.data.list[0])
        this.row = ress.data.list[0]
        return resolve(ress.data.list) // 最顶层数据渲染为region
      }
      if (node.level >= 1) {
        const {
          data: { list }
        } = await getzijidianapi(node.data)
        return resolve(list)
      }
    },
    // 导入
    daoru() {
      if (!this.value) return this.$message.warning('请先选择设备')
      this.$refs.ExportorInport.dialogVisible = true
    },
    daochu() {
      if (!this.value) return this.$message.warning('请先选择设备')
      axios({
        method: 'POST',
        url: `/biz/pio-microservice-biz/pio/equip/measure/point/set/day/user/exportExcel?deviceId=${this.value}`,
        responseType: 'blob'
      }).then((res) => {
        const blobContent = new Blob([res.data])
        // blob转地址
        const url = window.URL.createObjectURL(blobContent)
        // 开始导出
        saveAs(url, `测点信息.xls`)
      })
    },
    async getshebeilist(number, val) {
      // 目前树状图数据没有，deviceId参数暂时写死
      // const res = await getshebeilistapi({ deviceId: number, itemGroup: val || '' })
      this.loading = true
      const pageNo = this.pageNo - 1
      const {
        data: { list, totalCount }
      } = await getDevicePageapi({
        deviceId: number,
        itemGroup: val || '',
        pageSize: this.pageSize,
        pageNo,
        keyword: this.input2
      })
      this.tableData = list
      this.total = totalCount
      this.loading = false
    },
    handleNodeClick(val) {
      this.row = val
      this.value = val.id
      this.getcaijixialalist(val.id)
      this.getshebeilist(val.id, this.val)
    },
    handleSelectionChange(val) {
      this.changeselect = val
      this.mulist = val.map((ele) => ele.id)
    },
    changeselectdan(val) {
      this.val = val
      this.getshebeilist(this.value, val)
    },
    changeinput() {
      this.getshebeilist(this.row.id, this.val)
    },
    handleSelect(val) {
      console.log(val, 555)
    },
    // ---------------------
    async changinput1() {
      // this.options = this.option.filter(ele => ele.name.indexOf(this.$refs.select.query) !== -1)
      const res = await getsousuoapi({ name: this.$refs.select.query })
      this.options = res.data.list
      console.log(res.data.list)
    },
    shuxing() {
      this.getshebeilist(this.value, this.val)
    },
    async submit() {
      await this.$refs.form.validate()
      this.dialogVisibles = false
      await postfuzizenapi({
        deviceId: this.row.id,
        iotDeviceId: this.formdata.caiji,
        referDeviceId: this.formdata.fuzhi
      })
      this.getshebeilist(this.value, this.val)
      this.$message.success('复制成功')
      this.$refs.form.resetFields()
    },
    quxiaofuzhi() {
      this.dialogVisibles = false
      this.$refs.form.resetFields()
    },
    dellist(row) {
      if (!this.mulist[0] && !row.id) return this.$message.warning('请先勾选')
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          if (row.id) {
            await dellistapi({ id: [row.id] })
          } else {
            await dellistapi({ id: this.mulist })
          }
          this.getshebeilist(this.value, this.val)
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    pilianggai() {
      console.log(this.changeselect)
      if (this.changeselect.length === 0)
        return this.$message.warning('请先勾选')
      if (this.changeselect.every((ele) => ele.dataType === 'YC')) {
        this.$refs.dialogyaoce.dialogVisible = true
        console.log('yc')
      } else if (this.changeselect.every((ele) => ele.dataType === 'YX')) {
        this.$refs.dialogyaoxin.dialogVisible = true
        console.log('yx')
      } else if (this.changeselect.every((ele) => ele.dataType === 'LJ')) {
        this.$refs.dialogleiji.dialogVisible = true
        console.log('lj')
      } else if (this.changeselect.every((ele) => ele.dataType === 'YK')) {
        this.$refs.dialogyaokong.dialogVisible = true
        console.log('yk')
      } else if (this.changeselect.every((ele) => ele.dataType === 'YT')) {
        console.log('yt')
        this.$refs.dialogyaotiao.dialogVisible = true
      } else {
        this.$message.warning('请勾选同一数据类型的数据进行批量修改')
      }
    },

    // 树节点搜索
    async querySearch(queryString, cb) {
      setTimeout(async () => {
        const res = await getsousuoapi({ name: queryString })
        const restaurants = res.data.list
        cb(restaurants)
      }, 500)
      // 调用 callback 返回建议列表的数据
    },
    // 搜索选择
    handleSelect(item) {
      this.array = ['503750']
      const newarr = item.pathId.split(',')
      for (let i = 0; i < newarr.length; i++) {
        if (newarr[i]) {
          this.array.push(newarr[i])
        }
      }
      function getgaoliang(that) {
        let node = that.$refs.tree.getNode(item)
        if (node) {
          that.$refs.tree.setCurrentKey(String(item.id))
        } else {
          setTimeout(() => {
            getgaoliang(that)
          }, 500)
        }
      }
      getgaoliang(this)
      this.value = item.id.toString()
      this.row = item
      const namestring = item.name
      this.row.name = namestring.replace(/\[.*?\]|\(.*?\)/g, '')
      this.getshebeilist(item.id, this.val)
    },

    putjisuangongsi(row) {
      this.$refs.xunicedian.dialogVisible = true
      this.isxunicedianobj = row
    },
    putlists(row) {
      this.changeselect = [row]
      if (row.dataType === 'YC') {
        this.$refs.dialogyaoce.dialogVisible = true
      } else if (row.dataType === 'YX') {
        this.$refs.dialogyaoxin.dialogVisible = true
      } else if (row.dataType === 'LJ') {
        this.$refs.dialogleiji.dialogVisible = true
      } else if (row.dataType === 'YK') {
        this.$refs.dialogyaokong.dialogVisible = true
      } else if (row.dataType === 'YT') {
        this.$refs.dialogyaotiao.dialogVisible = true
      }
    },
    newxuni() {
      this.value
        ? (this.$refs.xunicedian.dialogVisible = true)
        : this.$message.warning('请先选择测点设备')
    },
    shuaxin() {
      this.getshebeilist(this.value, this.val)
    },
    async shangyi(row) {
      await postshangyiapi({ id: row.id })
      this.$message.success('上移成功')
      this.getshebeilist(this.value, this.val)
    },
    async xiayi(row) {
      await postxiayiapi({ id: row.id })
      this.$message.success('下移成功')
      this.getshebeilist(this.value, this.val)
    },
    handleCommand(val) {
      if (val == 'moban') {
        this.$refs.dialogmuban.dialogVisible = true
      } else if (val == 'fuzhi') {
        this.dialogVisibles = true
      } else if (val == 'zhiyou') {
        this.$refs.dialogfeimuban.dialogVisible = true
      }
    },
    beforeDestroy() {
      this.istreeshow = false
    }
  },
  watch: {
    input2(val) {
      setTimeout(() => this.getshebeilist(this.value, this.val), 500)
    },
    filterText(newValue) {
      this.filterText = newValue
        .replace(/^\[(.*?)\]/, '')
        .replace(/\((.*?)\)$/, '')
    }
  }
}
</script>

<style lang="scss" scoped>
.sure {
  margin-right: 10px;
  background-color: #169bd5 !important;
  color: #fff;
}
.title {
  font-size: 18px;
  font-weight: 100px;
}
::v-deep.el-select-dropdown__empty {
  display: none;
}
::v-deep .el-select-dropdown__wrap {
  max-width: 280px !important;
}

.select {
  padding-left: 10px;
  width: 270px !important;
}
.tablebox {
  height: 85%;
  // background-color: yellow;
}
.fenye {
  text-align: right;
  margin-top: 10px;
}
.bigbox {
  padding: 10px;
  background-color: #f1f1f1;
  display: flex;
  justify-content: space-between;
  height: 100%;
}
.liftbox {
  width: 300px;
  background-color: #fff;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  // border-radius: ;
}
.rightbox {
  margin-left: 10px;
  background-color: #fff;
  width: calc(100% - 310px);
  // height:300px;
  padding: 20px;
  box-sizing: border-box;
}
.righttop {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
}
.newzeng {
  background-color: #1890ff !important;
  color: #fff;
}
.feixin {
  width: 95px !important;
}
.treebox {
  margin-top: 10px;
  width: 100%;
  height: calc(100% - 60px);
  // border:1px solid #ccc;
  overflow: hidden;
  overflow-y: auto;
}
::v-deep .el-tree-node__content {
  font-size: 14px; /* 修改为你想要的字体大小 */
}
::v-deep .el-input__suffix {
  cursor: pointer;
}
</style>
